package com.wwwarehouse.resource_center.fragment.createobject.creategoods;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.adapter.rules.GoodsSelectLabelAdapter;
import com.wwwarehouse.resource_center.bean.goods.GoodsSelectLabelBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.GoodsEvent;
import com.wwwarehouse.resource_center.fragment.rules.TheParentFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @author Joseph on 2017/8/25.
 *         <p/>
 *         选择标签
 */

public class GoodsLabelSelectLabelsFragment extends TheParentFragment {

    public RecyclerView mRvContent;
    public GoodsSelectLabelAdapter mAdapter;
    public List<GoodsSelectLabelBean.ListBean> tagBeanList = new ArrayList<>();
    private int pos; //当前第几页
    private GoodsSelectLabelBean.ListBean msg;
    private int num; //总共页数
    public static final int SELECT_LABER_BYNAME = 2;  //根据标签名模糊查找标签
    private String searchName = "";
    private ArrayList<GoodsSelectLabelBean.ListBean> selectedLabel; //已选择的标签

    @Override
    protected int getContentId() {
        return R.layout.fragment_rule_select_application_objectst;
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof GoodsLabelSelectLabelsFragment)
            mActivity.setTitle(getString(R.string.goods_select_the_label));
    }

    @Override
    public void onSuccess(CommonClass commonClass, int i) {
        switch (i) {
            case SELECT_LABER_BYNAME:
                if (TextUtils.equals("0", commonClass.getCode())) {
                    GoodsSelectLabelBean goodsSelectLabelBean = JSON.parseObject(commonClass.getData().toString(), GoodsSelectLabelBean.class);
                    tagBeanList = goodsSelectLabelBean.getList();
                    if (null != selectedLabel) {
                        for (int i1 = 0; i1 < tagBeanList.size(); i1++) {
                            for (int i2 = 0; i2 < selectedLabel.size(); i2++) {
                                if (tagBeanList.get(i1).getLabelUkid().equals(selectedLabel.get(i2).getLabelUkid())) {
                                    tagBeanList.get(i1).setSelect(true);
                                }
                            }
                        }
                    }
                    final ViewTreeObserver observer = mRvContent.getViewTreeObserver();
                    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            observer.removeGlobalOnLayoutListener(this);
                            setHeight(mRvContent.getHeight(), mRvContent.getWidth());
                        }
                    });
                }
        }
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return null;
    }

    @Override
    public void onReLoad(int code) {

    }

    @Override
    protected void init(View view) {
        EventBus.getDefault().register(this);
        mRvContent = findView(view, R.id.rv_content);
        mRvContent.setLayoutManager(new GridLayoutManager(mActivity, 3) {
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }

            @Override
            public boolean canScrollVertically() {
                return false;
            }

        });
    }

    public void setHeight(int height, int Width) {
        LogUtils.showInfoLog("setHeight height:" + height + "Width" + Width);
        if (null == mAdapter) {
//            for (int i = 0; i < tagBeanList.size(); i++) {
//                LogUtils.showInfoLog("3333333333tagBeanList.size()"+tagBeanList.size()+"UKID:"+tagBeanList.get(i).getLabelUkid()+"Name:"+tagBeanList.get(i).getLabelName()+"isSelect:"+tagBeanList.get(i).isSelect());
//            }
            mAdapter = new GoodsSelectLabelAdapter(mActivity, tagBeanList, height, Width);
            mRvContent.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        //如果是最后一页，是时候通知获取数据刷新了
        if (pos == num) {
            LogUtils.showInfoLog("pos:" + pos + "num:" + num);
            EventBus.getDefault().post(new GoodsEvent(GoodsEvent.GOODS_ADD_LABEL_NOTICE, tagBeanList.size()));
        }
//        mAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void loadDatas() {
        Bundle b = getArguments();
//        tagBeanList = b.getParcelableArrayList("dataArry");
        pos = b.getInt("pos");
        num = b.getInt("num");
        searchName = b.getString("labelName");
//        for (int i = pos * num; i < num + pos * num; i++) {
//            if (i >= 0 && i < taskUnits.size()) {
//                tagBeanList.add(taskUnits.get(i));
//            }
//        }
//        mRvContent.addItemDecoration(new SpaceItemDecoration(10));
        GoodsSelectLabelBean.ListBean msg = b.getParcelable("data");
        selectedLabel = b.getParcelableArrayList("selectedLabel");
        if (msg != null) {
            tagBeanList.add(msg);
            LogUtils.showInfoLog("tagBeanList.add(msg):" + msg.getLabelName());
            final ViewTreeObserver observer = mRvContent.getViewTreeObserver();
            observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    observer.removeGlobalOnLayoutListener(this);
                    if (null == mAdapter) {
                        mAdapter = new GoodsSelectLabelAdapter(mActivity, tagBeanList, mRvContent.getHeight(), mRvContent.getWidth());
                        mRvContent.setAdapter(mAdapter);
                    }
                    mAdapter.notifyDataSetChanged();
                }
            });
        } else {
            LogUtils.showInfoLog("GetData" + "pos:" + pos + "num:" + num);
            GetData(pos, searchName);
        }
    }

    public void onEventMainThread(GoodsEvent event) {
        //新增的标签刷新最后一页数据并默认选中
        switch (event.getCode()) {
            case GoodsEvent.GOODS_ADD_LABEL_REFRESH:
                if (pos == Integer.parseInt(event.getMsg())) {
//                    msg = (TaskUnitBean.TaskUnitsBean) event.getData();
//                    msg.setSelect(true);
//                    LogUtils.showInfoLog("GoodsLabelSelectLabelsFragment111111:"+ msg.getUnitName());
//                    tagBeanList.add(msg);
//                    setHeight(mRvContent.getHeight(),mRvContent.getWidth());
                    break;
                }
        }
    }

    public void GetData(int pos, String searchName) {
        Map<String, Object> map = new HashMap();
        Map<String, Number> query = new HashMap<>();
        if (TextUtils.isEmpty(searchName)) {
            searchName = "";
        }
        map.put("labelName", searchName);
        map.put("businessId", sp.getValue("businessId"));
        query.put("page", pos + 1);
        query.put("size", 24);
        map.put("query", query);
        httpPost(ResourceConstant.SELECT_LABER_BYNAME, map, SELECT_LABER_BYNAME, false, "");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
